package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.RegionMapper;
import com.example.entity.PageVO;
import com.example.entity.Region;
import com.example.service.RegionService;
import com.example.utils.PageQueryUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 14990
 * @description 针对表【region(区划表)】的数据库操作Service实现
 * @createDate 2023-02-28 09:11:24
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {
    @Resource
    RegionMapper regionMapper;

    @Override
    public Page<Region> queryByPage(PageVO<Region> pageVO) {
        Region param = pageVO.getParam();
        Wrapper<Region> wrapper = null;
        if (param != null) {
            LambdaQueryWrapper<Region> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            //构建查询条件
            wrapper = lambdaQueryWrapper;
        }
        PageQueryUtil.buildPage(pageVO, wrapper);
        return super.page(pageVO.getPage(), pageVO.getWrapper());
    }

    @Override
    public void grabPage(int level) {
//        LambdaQueryWrapper<Region> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Region::getLevel, level).isNotNull(Region::getUrl).eq(Region::isFlag, false);
//        List<Region> regionList = regionMapper.selectList(queryWrapper);
//        for (Region region : regionList) {
//            try {
//                String url = Region.ROOT_URL +
//                        (level > 2 ? region.getId().substring(0, 2) + "/" : "/") +
//                        (level > 3 ? region.getId().substring(2, 4) + "/" : "/") +
//                        region.getUrl();
//                Elements elements = Region.select(url);
//                Set<Region> set = elements.stream()
//                        .map(item -> Region.trans(item, region.getId(), level))
//                        .collect(Collectors.toSet());
//                if (!set.isEmpty()) {
//                    saveBatch(set);
//                }
//                Thread.sleep(1000);
//                region.setFlag(true);
//            } catch (Exception e) {
//                e.printStackTrace();
//                region.setFlag(false);
//            }
//            updateById(region);
//        }
    }

    @Override
    public List<Region> queryList(String pid) {
        LambdaQueryWrapper<Region> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Region::getPid, pid);
        return regionMapper.selectList(queryWrapper);
    }
}




